#include "videoview.h"
#include "ui_videoview.h"
#include <iostream>

VideoView::VideoView(QWidget *parent)
    : QWidget(parent), ui(new Ui::VideoView)
{
    //setting up the different variable and the picture flow
//and setting up the phonon objects

    ui->setupUi(this);
    ui->flow->setReflectionEffect(PictureFlow::BlurredReflection);
    ui->flow->setSlideSize(QSize(250,200));
    mediaobject = new Phonon::MediaObject(this);
    mediaobject4wc = new Phonon::MediaObject(this);
    mediaobject4wc->setPrefinishMark(100);
    Phonon::createPath(mediaobject,ui->vidWig);
    Phonon::createPath(mediaobject4wc,ui->vidWig4wc);
    connect(mediaobject, SIGNAL(finished()), this, SLOT(stop()));//connecting the slots
    connect(mediaobject4wc, SIGNAL(prefinishMarkReached(qint32)),this,SLOT(webcamVideoDone()));//connecting the slots
    connect(this, SIGNAL(recordTo(QString)), ui->webcam, SLOT(record(QString)));//connecting the slots
    index = 0;
    total = 0;
    ui->playpausebutton->setEnabled(false);//setting the button invisible
    ui->stopRec->setVisible(false);//setting the button invisible
    ui->vidWig4wc->setVisible(false);//setting the widget invisible
    ui->learnedCheck->setVisible(false);//setting the lerned check visible
}
/*
fuction used ot clear the flow, source and phrases
*/
void VideoView::clear()
{
    ui->flow->clear();//clearing the picture flow
    index = 0;
    total = 0;
    sources.clear();//clearing the sources
    phrases.clear();//clearing the phrases
}
/*
function used to set the users learned and not lerned videos
*/
void VideoView::setUser(QString name)
{
    user = name;//getting the users name

    QFile progress(QString("users/").append(name));//opening the users file
    if (!progress.open(QIODevice::ReadOnly))
        std::cout << "Couldn't find user file!\n";
    while (!progress.atEnd())
    {
        learnedPhrases += progress.readLine().trimmed().toUpper();//reading in the learned phrases
        //std::cout << "Already learned\n";
    }
    ui->learnedCheck->setVisible(true);
}
/*
function used to start the recording
*/
void VideoView::startRecording()
{
    //stop();
    mediaobject->play();
    emit recordTo(QString("temp.mpg"));//starts the recording to a temp file if no user is selected
}
/*
this function is called when the recording is finished
*/

void VideoView::doneRecording()
{
    stop();//stoppoing anz playing video
    ui->webcam->setVisible(false);//setting widget invisible
    ui->vidWig4wc->setVisible(true);//setting widget visible
    //sleep(100);
    mediaobject4wc->clear();//clearing the media objuct
    mediaobject4wc->setCurrentSource(Phonon::MediaSource(QString("temp.mpg")));//setting the new media source
    mediaobject4wc->play();//playing new media

    mediaobject->stop();//stopping library vid
    mediaobject->play();//playing library vid

    setStopRecVisible(false);//setting the stop record video button invisible
    ui->playpausebutton->setEnabled(true);//setting the play pause button visible
    ui->stopbutton->setEnabled(true);//setting the stop button visible
}
/*
function used when the webcam is done
*/
void VideoView::webcamVideoDone()
{

    mediaobject4wc->stop();//stop the mediaobject
    //mediaobject4wc->clear();
    //mediaobject4wc->setCurrentSource(Phonon::MediaSource());
    ui->vidWig4wc->setVisible(false);//setting the widget invisible
    ui->webcam->setVisible(true);//setting the webcam visible

}
/*
  this function is used to track the users prograss withe each file
  */
void VideoView::learnedThis(bool value)
{
    ui->learnedCheck->setChecked(value);//sets the learnec check
    //std::cout << "in learned this!\n";
    if (value)
    {
        //ui->flow->tintCurrentSlideGreen(true);
        if(!learnedPhrases.contains(phrases.at(index)))
        {
            learnedPhrases += phrases.at(index);//adds the learned phrase to the list
            //ui->flow->tintCurrentSlideGreen(true);
            QFile progress(QString("users/").append(user));//opens the users file
            if (!progress.open(QIODevice::WriteOnly | QIODevice::Truncate))
                //std::cout << "Couldn't find user file!\n";
                return;
            QTextStream out(&progress);
            foreach (QString learned, learnedPhrases)
                out << learned.append("\n");//writes the list to the file
            progress.close();//closes the writer
            return;
        }
    }
    else
    {
        //ui->flow->tintCurrentSlideGreen(false);
        learnedPhrases.removeAt(learnedPhrases.indexOf(phrases.at(index)));//removes the phrase from the list in memory
        QFile progress(QString("users/").append(user));//creates the file
        if (!progress.open(QIODevice::WriteOnly | QIODevice::Truncate))

            return;
        QTextStream out(&progress);
        foreach (QString learned, learnedPhrases)
            out << learned.append("\n");//writing the data to the file
        progress.close();//closing the file
    }
}

VideoView::~VideoView()
{
    delete ui;
}
/*
used to play the videos
*/
void VideoView::play()
{
    if (mediaobject->state() == Phonon::PlayingState)//if a video is playing pause it
        mediaobject->pause();
    else mediaobject->play();//otherwis play it
    if (mediaobject4wc->currentSource().type()
        != Phonon::MediaSource::Invalid
                && mediaobject4wc->totalTime() > 100)
    {
        ui->webcam->setVisible(false);
        ui->vidWig4wc->setVisible(true);
        if (mediaobject4wc->state() == Phonon::PlayingState)//if a video is playing pause it
            mediaobject4wc->pause();
        else mediaobject4wc->play();//otherwis play it
    } else {
        ui->webcam->setVisible(true);//make webcam visible
        ui->vidWig4wc->setVisible(false);//make vidwog invisible
    }

    ui->stopbutton->setEnabled(true);//enable the stop button
}
/*
used to sop the video
*/
void VideoView::stop()
{
    ui->stopbutton->setEnabled(false);//disable the stop button
    mediaobject->stop();//stop the video
    mediaobject4wc->stop();//stop the video
}
/*
setting the visiblity of the recore and stop recor button
*/
void VideoView::setStopRecVisible(bool state)
{
    ui->stopRec->setVisible(state);
    ui->record->setVisible(!state);
}

/*
user to play the next video in the list
*/
void VideoView::playNext()
{
    if (index < total-1)
    {
        index++;//incrimants the index
        stop();//stops the plaing video
        mediaobject->setCurrentSource(sources.at(index));//sets the new media source
        mediaobject4wc->stop();
        mediaobject4wc->clear();
        mediaobject4wc->setCurrentSource(Phonon::MediaSource());
        QDir().remove("temp.mpg");

        ui->phrase->setText(QString("Phrase: ").append(phrases.at(index)));//sets the phrase from the file name
        if (index == total-1) ui->nextbutton->setEnabled(false);
        ui->previousbutton->setEnabled(true);//enable the prevois button
        ui->vidWig4wc->setVisible(false);//sets the vidwig invisible
        ui->webcam->setVisible(true);//set the webcam visible

        ui->learnedCheck->setChecked(learnedPhrases.contains(phrases.at(index)));//sets the learned for the phrase

    }
}
/*
function used to set the in dex and the prase
*/
void VideoView::setIndex(int i)
{
    if (index == i) return;
    index = i;
    stop();//stop andy playing video
    mediaobject->setCurrentSource(sources.at(index));//set the media source at the index
    mediaobject4wc->clear();
    mediaobject4wc->setCurrentSource(Phonon::MediaSource());
    QDir().remove("temp.mpg");

    ui->phrase->setText(QString("Phrase: ").append(phrases.at(index)));//set the phrase at he index point
    ui->nextbutton->setEnabled( (index != total-1) );//enabel or disable the next button
    ui->previousbutton->setEnabled(index != 0);//enable or disable the previous button
    ui->learnedCheck->setChecked(learnedPhrases.contains(phrases.at(index)));//sets the learned for the phrase
}
/*
used in the clicking of the previous burron
*/

void VideoView::playPrevious()
{
    if (index > 0)
    {
        ui->nextbutton->setEnabled(true);//enable the bext button
        index--;//decriment the index
        stop();//stop any playing video
        mediaobject->setCurrentSource(sources.at(index));//set the media source according to the index
        mediaobject4wc->stop();
        mediaobject4wc->clear();
        mediaobject4wc->setCurrentSource(Phonon::MediaSource());
        QDir().remove("temp.mpg");

        ui->phrase->setText(QString("Phrase: ").append(phrases.at(index)));//est the phrase
        if (index == 0) ui->previousbutton->setEnabled(false);//if the index is 0 disable the previous button
        ui->vidWig4wc->setVisible(false);//set the vidwig invisible
        ui->webcam->setVisible(true);//set the webcam visible
        ui->learnedCheck->setChecked(learnedPhrases.contains(phrases.at(index)));//sets the learned for the phrase
    }
}
/*
function used to add items to the list
*/
void VideoView::addList(QStringList files)
{
    total += files.size();//setting the index size
    foreach (QString string, files) {
        QString copy(string);//getting the string name
        Phonon::MediaSource tempsource(QString(string.replace(QString("jpg"),QString("wmv"))));//replacing the jpeg with the
                                                                                                //wmv
        sources.append(tempsource); //appending the new sources to the old

        ui->flow->addSlide(QImage(copy));//adding the images to the picture flow
        QFileInfo fi(string);//getting the file name
        phrases.append(fi.baseName().toUpper());//appending the phrases

    }
    QString temp; temp = files.at(0);//initializing the temp file name string
    temp.replace(QString("jpg"),QString("wmv"));//replacing the jpg with the wmv
    Phonon::MediaSource source (temp);//setting the media source
    mediaobject->setCurrentSource(source);//setting the mediaobjects source
    ui->flow->setCenterIndex(0);//setting the flows starting index
    QFileInfo fi(temp);//getting the file name
    index = 0;//setting the index
    ui->phrase->setText(QString("Phrase: ").append(fi.baseName().toUpper()));//setting the phrase
    ui->playpausebutton->setEnabled(true);//enabling the pause button
    if (index > 0) ui->previousbutton->setEnabled(true);//enabling/disabling the previous button
    if (index < total -1) ui->nextbutton->setEnabled(true);//enabling/disabling the next button
}
/*
functio used to add files to the list
*/
void VideoView::addFiles()
{
    QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Image Files"),
        QDesktopServices::storageLocation(QDesktopServices::HomeLocation),QString("Images: *.jpg (*.jpg)"));//setting up the dialog to add the files

    if (files.isEmpty())
        return;

    addList(files);//adding the files to the list
}
//adding the lessons files to the list
void VideoView::addFiles(QStringList files)
{
    clear();
    addList(files);
}

